import requests
from ..config import Config

class APIClient:
    """第三方API请求客户端"""
    
    def __init__(self):
        self.base_url = "http://hkcqjy.com.cn:8220"
        self.token = None  # 初始化时将token设为None

    def get_token(self):
        """获取API访问令牌"""
        url = f"{self.base_url}/api/auth/token"
        payload = {
            "username": Config.API_USERNAME,
            "password": Config.API_PASSWORD
        }
        try:
            response = requests.post(url, json=payload, timeout=10)
            response.raise_for_status()
            self.token = response.json().get('token')  # 从响应中获取token并更新实例属性
            if not self.token:
                raise Exception("未能从API响应中获取到有效的token")
            return self.token
        except requests.exceptions.RequestException as e:
            raise Exception(f"API请求失败: {str(e)}")

    def fetch_inventory_data(self):
        """获取库存原始数据"""
        if not self.token:  # 检查token是否存在，不存在则请求
            self.get_token()
        
        url = f"{self.base_url}/api/inventory-endpoint"
        headers = {
            "Authorization": f"Bearer {self.token}",
            "Content-Type": "application/json"
        }
        
        try:
            response = requests.get(url, headers=headers, timeout=30)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            raise Exception(f"API请求失败: {str(e)}")

# 单例客户端实例
api_client = APIClient()